package org.liang.code.jms.queue.more;

import jakarta.jms.*;
import org.apache.activemq.artemis.jms.client.ActiveMQJMSConnectionFactory;
import org.liang.code.utils.jms.JMSCommons;

/**
 * 追溯地址 发布者先发布消息 后来的订阅者可以收到订阅前的消息
 */
public class RMCTMain {

    public static void main(String[] args) throws InterruptedException {

        // 创建工厂
        ActiveMQJMSConnectionFactory factory = new ActiveMQJMSConnectionFactory(JMSCommons.CORE_URL, JMSCommons.USERNAME, JMSCommons.PASSWORD);
        // 创建JMSContext
        JMSContext context = factory.createContext(Session.AUTO_ACKNOWLEDGE);
        // 创建发布者
        JMSProducer producer = context.createProducer();

        // 先发布30条消息
        for (int i = 0; i < 30; i++) {
            String body = JMSCommons.counter.getAndAdd(1) + "";
            TextMessage message = context.createTextMessage(body);
            // 发布消息
            producer.send(context.createTopic(JMSCommons.CORE_RMCT), message);
        }

        // 最好先把主题下的队列建立好,否则第一次会收不到数据
        Thread.sleep(5000);
        ActiveMQJMSConnectionFactory factory2 = new ActiveMQJMSConnectionFactory(JMSCommons.CORE_URL, JMSCommons.USERNAME, JMSCommons.PASSWORD);
        factory2.setClientID("giao");
        JMSContext context2 = factory2.createContext(Session.AUTO_ACKNOWLEDGE);
        JMSConsumer miao = context2.createDurableConsumer(context.createTopic(JMSCommons.CORE_RMCT), "miao");
        for (int i = 0; i < 30; i++) {
            Message receive = miao.receive(100);
            System.out.println(receive);
        }

        miao.close();
        context2.close();
        factory2.close();
        context.close();
        factory.close();
    }
}
